package com.xbongbong.paas.service.log.crm.operation.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.service.log.crm.operation.AbstractOperationLogHandle;
import com.xbongbong.paas.service.log.crm.operation.CompetitorAnalysisOperationLogHandler;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.competitor.pojo.dto.log.CompetitorAnalysisExplainSaveLogDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.CompetitorAnalysisUpdateLogDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.LinkCompetitorLogDTO;
import com.xbongbong.pro.competitor.pojo.dto.log.SwotUpdateLogDTO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.log.pojo.dto.AddOperationLogDTO;
import com.xbongbong.pro.log.pojo.dto.DeleteBatchOperationLogDTO;
import com.xbongbong.pro.log.pojo.dto.DeleteOperationLogDTO;
import com.xbongbong.pro.log.pojo.dto.UpdateBatchOperationLogDTO;
import com.xbongbong.pro.log.pojo.dto.UpdateOperationLogDTO;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.CompetitorAnalysisModel;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author gaojie
 * @version v1.0
 * @date 2022/9/13 19:02
 * @description
 */
@Slf4j
@Service("competitorAnalysisOperationHandlerImpl")
public class CompetitorAnalysisOperationHandlerImpl extends AbstractOperationLogHandle implements CompetitorAnalysisOperationLogHandler {

    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private CompetitorAnalysisModel competitorAnalysisModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;


    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
    }

    @Override
    public void add(AddOperationLogDTO addOperationLogDTO) {

    }

    @Override
    public void update(UpdateOperationLogDTO updateOperationLogDTO) {

    }

    @Override
    public void updateBatch(UpdateBatchOperationLogDTO updateBatchOperationLogDTO) {

    }

    @Override
    public void delete(DeleteOperationLogDTO deleteOperationLogDTO) {

    }

    @Override
    public void deleteBatch(List<InfoArrPojo> infoArrPojoList, DeleteBatchOperationLogDTO deleteBatchOperationLogDTO) {

    }

    @Override
    @Async("sysLogThreadPool")
    public void linkCompetitor(LinkCompetitorLogDTO linkCompetitorLogDTO) {
        try {
            String corpid = linkCompetitorLogDTO.getCorpid();
            String userId = linkCompetitorLogDTO.getUserId();
            String userName = linkCompetitorLogDTO.getLoginUserName();
            Long competitorId = linkCompetitorLogDTO.getCompetitorId();
            Long oppotunityId = linkCompetitorLogDTO.getOpportunityId();

            Map<String, String> nameMap = getName(corpid, competitorId, oppotunityId);
            String competitorName = nameMap.get("competitorName");
            String competitorFormName = nameMap.get("competitorFormName");
            String opportunityName = nameMap.get("opportunityName");
            String opportunityFormName = nameMap.get("opportunityFormName");

            // 组装日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_LINK_COMPETITOR_WITH_OPPORTUNITY), userName, competitorFormName, competitorName, opportunityFormName, opportunityName);
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.COMPETITOR, OperateTypeEnum.NEW,
                    competitorId.toString(), competitorName, memo, linkCompetitorLogDTO.getHttpHeader());
        }catch (Exception e){
            log.error("CompetitorAnalysisOperationHandlerImpl#linkCompetitor exception:{}",e);
        }

    }


    /**
     *  取消关联竞争对手
     * @param linkCompetitorLogDTO
     */
    @Override
    @Async("sysLogThreadPool")
    public void cancelLinkCompetitor(LinkCompetitorLogDTO linkCompetitorLogDTO) {

        try {
            String corpid = linkCompetitorLogDTO.getCorpid();
            String userId = linkCompetitorLogDTO.getUserId();
            String userName = linkCompetitorLogDTO.getLoginUserName();
            Long competitorId = linkCompetitorLogDTO.getCompetitorId();
            Long oppotunityId = linkCompetitorLogDTO.getOpportunityId();

            Map<String, String> nameMap = getName(corpid, competitorId, oppotunityId);
            String competitorName = nameMap.get("competitorName");
            String competitorFormName = nameMap.get("competitorFormName");
            String opportunityName = nameMap.get("opportunityName");
            String opportunityFormName = nameMap.get("opportunityFormName");

            // 组装日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_CANCEL_LINK_COMPETITOR_WITH_OPPORTUNITY), userName, competitorFormName, competitorName, opportunityFormName, opportunityName);
            mongoLogHelp.buildLog(corpid,userId,userName, OperateModuleTypeEnum.COMPETITOR, OperateTypeEnum.DELETE,
                    competitorId.toString(),competitorName,memo,linkCompetitorLogDTO.getHttpHeader());
        }catch (Exception e){
            log.error("CompetitorAnalysisOperationHandlerImpl#cancelLinkCompetitor exception:{}",e);
        }
    }

    @Override
    @Async("sysLogThreadPool")
    public void editCompetitorAnalysis(CompetitorAnalysisUpdateLogDTO dto) {
        try {
            String corpid = dto.getCorpid();
            String userId = dto.getUserId();
            String userName = dto.getLoginUserName();
            JSONObject oldData = dto.getOldData();
            JSONObject newData = dto.getNewData();
            Long competitorId = dto.getCompetitorId();
            Long opportunityId = dto.getOpportunityId();
            PaasFormExplainEntity paasFormExplainEntity = dto.getPaasFormExplainEntity();

            Map<String, String> nameMap = getName(corpid, competitorId, opportunityId);
            String competitorName = nameMap.get("competitorName");
            String competitorFromName = nameMap.get("competitorFormName");
            String opportunityName = nameMap.get("opportunityName");
            String opportunityFromName = nameMap.get("opportunityFormName");
            // 组装日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EDIT_COMPETITOR_ANALYSIS), userName, competitorFromName, competitorName, opportunityFromName, opportunityName);
            List<DetailLogPojo> detailLogPojoList = logHelp.detailLog4CompetitorAnalysis(oldData, newData,paasFormExplainEntity);
            if (Objects.nonNull(detailLogPojoList)) {
                mongoLogHelp.buildLog4DetailArr(detailLogPojoList,corpid,userId,userName,OperateModuleTypeEnum.COMPETITOR,OperateTypeEnum.EDIT,competitorId.toString(),competitorName,memo,dto.getHttpHeader());
            }
        }catch (Exception e){
            log.error("CompetitorAnalysisOperationHandlerImpl#editCompetitorAnalysis exception:{}",e);

        }

    }

    @Override
    @Async("sysLogThreadPool")
    public void editSwotAnalysis(SwotUpdateLogDTO dto) {
        try {
            String corpid = dto.getCorpid();
            String userId = dto.getUserId();
            String userName = dto.getLoginUserName();
            Long competitorId = dto.getCompetitorId();
            Long opportunityId = dto.getOpportunityId();
            JSONArray oldSwot = Optional.ofNullable(dto.getOldSwot()).orElse(new JSONArray());
            JSONArray newSwot = Optional.ofNullable(dto.getNewSwot()).orElse(new JSONArray());

            Map<String, String> nameMap = getName(corpid, competitorId, opportunityId);
            String competitorName = nameMap.get("competitorName");
            String competitorFormName = nameMap.get("competitorFormName");
            String opportunityName = nameMap.get("opportunityName");
            String opportunityFormName = nameMap.get("opportunityFormName");

            // 获取竞争对手分析表单解释
            PaasFormExplainEntity competitorAnalysisFormExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode(),corpid);
            if (Objects.isNull(competitorAnalysisFormExplain)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(),"competitorAnalysisFormExplain NullException");
            }
            // 组装日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EDIT_SWOT_ANALYSIS), userName, competitorFormName, competitorName, opportunityFormName, opportunityName);

            List<DetailLogPojo> detailLogPojoList = logHelp.detailLog4CompetitorSwotAnalysis(oldSwot, newSwot,competitorAnalysisFormExplain);
            if (detailLogPojoList == null){
                return;
            }
            mongoLogHelp.buildLog4DetailArr(detailLogPojoList,corpid,userId,userName,OperateModuleTypeEnum.COMPETITOR,OperateTypeEnum.EDIT,competitorId.toString(),competitorName,memo,dto.getHttpHeader());
        }catch (Exception e){
            log.error("CompetitorAnalysisOperationHandlerImpl#editSwotAnalysis exception:{}",e);
        }
    }

    @Override
    @Async("sysLogThreadPool")
    public void saveFormExplain(CompetitorAnalysisExplainSaveLogDTO logDTO) {
        try {
            String corpid = logDTO.getCorpid();
            String userId = logDTO.getUserId();
            String userName = logDTO.getLoginUserName();
            JSONObject oldExplain = logDTO.getOldExplain();
            JSONObject newExplain = logDTO.getNewExplain();
            Long formId = logDTO.getFormId();
            PaasFormEntityExt paasForm = paasFormModel.getByKey(formId, corpid);
            String formName = paasForm.getName();
            List<DetailLogPojo> detailArr = logHelp.getDetailArr4Normal(corpid, OperateModuleTypeEnum.PAAS_FORM_EXPLAIN, oldExplain, newExplain);
            if (Objects.nonNull(detailArr)) {
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_EXPLAIN), userName, formName);
                String opObjectName = formName + I18nMessageUtil.getMessage(I18nStringConstant.FIELD_EXPLAIN);
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM_EXPLAIN, OperateTypeEnum.EDIT, formId.toString(), formName, memo, logDTO.getHttpHeader());
            }
        }catch (Exception e){
            log.error("CompetitorAnalysisOperationHandlerImpl#saveFormExplain exception:{}",e);
        }
    }


    /**
     * 获取竞争对手、机会名称及表单名称
     * @param corpid
     * @param competitorId
     * @param opportunityId
     * @return
     */
    private Map<String, String> getName(String corpid,Long competitorId,Long opportunityId){
        Map<String, String> nameMap = new HashMap<>();
        try {
            //获取竞争对手表单名称和竞争对手名称
            CompetitorEntity competitor = competitorModel.getByKey(competitorId, corpid);
            Long competitorFormId = competitor.getFormId();
            String competitorName = FastJsonHelper.getStringOrDefault(competitor.getData(), CompetitorEnum.NAME.getAttr(), "");
            PaasFormEntityExt competitorFrom = paasFormModel.getByKey(competitorFormId, corpid);
            String competitorFormName = competitorFrom.getName();
            // 获取销售机会表单名称和销售机会名称
            OpportunityEntityExt opportunity = opportunityModel.getByKey(opportunityId, corpid);
            Long opportunityFormId = opportunity.getFormId();
            String opportunityName = FastJsonHelper.getStringOrDefault(opportunity.getData(), SalesOpportunityEnum.NAME.getAttr(), "");
            PaasFormEntityExt opportunityFrom = paasFormModel.getByKey(opportunityFormId, corpid);
            String opportunityFormName = opportunityFrom.getName();


            //组装返回参数
            nameMap.put("competitorName",competitorName);
            nameMap.put("competitorFormName",competitorFormName);
            nameMap.put("opportunityName",opportunityName);
            nameMap.put("opportunityFormName",opportunityFormName);
            nameMap.put("competitorFormId",competitorFormId.toString());
        }catch (Exception e){
            log.error("CompetitorAnalysisOperationHandlerImpl#getName exception:{}",e);
        }
        return nameMap;
    }
}
